

const express = require('express');
const ejs = require('ejs');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const errorHandler = require('errorhandler');
const session = require('express-session');
const passport = require('passport');
const routes = require('./routes');

// Express配置
const app = express();
app.engine('ejs', ejs.__express);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, './views'));
app.use(cookieParser());
app.use(bodyParser.json({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(errorHandler());
app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

// Passport配置
require('./auth');

// 首页
app.get('/', routes.site.index);
// 登录页面表单
app.get('/login', routes.site.loginForm);
// 登录请求
app.post('/login', routes.site.login);
// 退出登录
app.get('/logout', routes.site.logout);
// 登录后获取账号信息
app.get('/account', routes.site.account);

// 授权
// http://localhost:3000/dialog/authorize?response_type=code&client_id=abc123&scope=user&state=111&redirect_uri=https%3A%2F%2Fwww.baidu.com
app.get('/dialog/authorize', routes.oauth2.authorization);
app.post('/dialog/authorize/decision', routes.oauth2.decision);
app.post('/oauth/token', routes.oauth2.token);

// 登录后获取用户信息
app.get('/api/userinfo', routes.user.info);
app.get('/api/clientinfo', routes.client.info);


app.listen(process.env.PORT || 3000, () => {
    console.log('服务启动成功：', process.env.PORT || 3000);
});

// Required for @now/node, optional for @now/node-server.
module.exports = app;
